package keyboard.controller.api;

import commonUtil.excption.WebResult;
import keyboaUtil.commonUtil.string.StringUtil;
import keyboaUtil.userData.MyCookie;
import keyboard.entity.User;
import keyboard.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 2B键盘
 * @create 2018-04-04 1:53
 * @desc member控制器
 **/
@Controller
@RequestMapping("/user")
public class UserAPI {

    @Autowired
    UserService service;

    private User entity;

    private String identity;
    private String password;

    /**
     * 用户登陆
     *
     * @param request
     * @return
     */
    @RequestMapping("/toLogin.do")
    @ResponseBody
    public WebResult login(HttpServletRequest request, HttpServletResponse response) {

        entity = new User();

        HttpSession session = request.getSession();

        String identity = request.getParameter("identity");
        String password = request.getParameter("password");

        if (!StringUtil.isStringNotNull(identity)) {
            return WebResult.fail("账号不能为空!");
        }
        if (!StringUtil.isStringNotNull(password)) {
            return WebResult.fail("密码不能为空!");
        }
        entity.setIdentity(identity);
        entity.setPassword(password);

        entity = service.login(entity);
        if (entity == null) {
            return WebResult.fail("账号或密码错误");
        }

        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(MyCookie.KEYBOARD_IDENTITY)) {
                this.identity = cookie.getValue();
            }
            if (cookie.getName().equals(MyCookie.KEYBOARD_PASSWORD)) {
                this.password = cookie.getValue();
            }
        }
        if (this.identity == null && this.password == null) {
            MyCookie.deleteCookie(response);
            Cookie userCookie = new Cookie(MyCookie.KEYBOARD_IDENTITY,
                    entity.getIdentity());
            Cookie passCookie = new Cookie(MyCookie.KEYBOARD_PASSWORD,
                    entity.getPassword());
            userCookie.setMaxAge(((60 * 60) * 24) * 7);
            passCookie.setMaxAge(((60 * 60) * 24) * 7);
            userCookie.setPath("/");
            passCookie.setPath("/");
            response.addCookie(userCookie);
            response.addCookie(passCookie);
            session.setAttribute(entity.getIdentity(), entity);
        }
        return WebResult.success("完美").add("member", entity);

    }


}
